/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * QuickStartListDialog.java
 *
 * Created on 2011-5-10, 13:01:01
 */
package org.lifxue.jqda.ui;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.data.bean.AppInfoBean;
import org.lifxue.jqda.util.GlobalConstant;
import org.lifxue.jqda.util.GlobalVar;

/**
 *
 * @author lifxue
 */
public class QuickStartListDialog extends javax.swing.JDialog {

    private static Log logger = LogFactory.getLog(QuickStartListDialog.class);
    private static QuickStartListDialog QSList;

    public static QuickStartListDialog getInstance(boolean modal) {
        synchronized (QuickStartListDialog.class) {
            if (QSList == null) {
                QSList = new QuickStartListDialog(modal);
            }
        }
        return QSList;
    }

    public QuickStartListDialog(boolean modal) {
        super(new javax.swing.JFrame(), modal);

        initComponents();
        initTableData();

        //屏幕位置
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = getSize();
        setLocation(new Point((screenSize.width - frameSize.width) / 2,
                (screenSize.height - frameSize.width) / 2));

    }

    /** Creates new form QuickStartListDialog */
    public QuickStartListDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        addjButton = new javax.swing.JButton();
        deljButton = new javax.swing.JButton();
        canceljButton = new javax.swing.JButton();
        savejButton = new javax.swing.JButton();
        scanjButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("快速启动程序列表");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "名称", "路径", "次数"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(2).setMinWidth(50);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(50);

        addjButton.setText("增加");
        addjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addjButtonActionPerformed(evt);
            }
        });

        deljButton.setText("删除");
        deljButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deljButtonActionPerformed(evt);
            }
        });

        canceljButton.setText("取消");
        canceljButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                canceljButtonActionPerformed(evt);
            }
        });

        savejButton.setText("保存");
        savejButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                savejButtonActionPerformed(evt);
            }
        });

        scanjButton.setText("自动扫描文件");
        scanjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                scanjButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 709, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addjButton)
                        .addGap(18, 18, 18)
                        .addComponent(deljButton)
                        .addGap(18, 18, 18)
                        .addComponent(scanjButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 347, Short.MAX_VALUE)
                        .addComponent(savejButton)
                        .addGap(18, 18, 18)
                        .addComponent(canceljButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(addjButton)
                            .addComponent(deljButton)
                            .addComponent(scanjButton))
                        .addContainerGap(33, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(canceljButton)
                            .addComponent(savejButton))
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButtonActionPerformed
        // TODO add your handling code here:
        //建立文件选择框对象
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "可执行文件", "exe", "bat", "lnk");
        fc.setFileFilter(filter);

        //设定文件选择框标题
        fc.setDialogTitle("选择可执行文件");
        //显示文件选择框，在选择后将结果储存到returnVal变量中
        int returnVal = fc.showSaveDialog(this);
        //如果用户选择了文件，并点击了"Opne/打开"按钮，显示用户选择的文件全名路径，
        //如果用户点击"Close/关闭"按钮，以及其它方式退出文件选择框，则什么也不做。
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (file == null) {
                return;
            }
            if (isExistPath(file)) {
                int type = JOptionPane.CLOSED_OPTION;
                String message = "你选择的文件已经在表格中了！";
                JOptionPane.showConfirmDialog(this, message, "提示信息", type);
                return;
            }
            addTableRow(file);

        }

    }//GEN-LAST:event_addjButtonActionPerformed

    private void canceljButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_canceljButtonActionPerformed
        // TODO add your handling code here:
        setVisible(false);
        dispose();
        QSList = null;

    }//GEN-LAST:event_canceljButtonActionPerformed

    private void deljButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButtonActionPerformed
        // TODO add your handling code here:
        javax.swing.table.DefaultTableModel model = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        int allcount = model.getRowCount();
        int[] rows = jTable1.getSelectedRows();
        for (int i = 0; i < rows.length; i++) {
            int row = jTable1.getSelectedRow();
            model.removeRow(row);
        }

    }//GEN-LAST:event_deljButtonActionPerformed

    private void savejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savejButtonActionPerformed
        // TODO add your handling code here:
        //保存数据到文件和全局变量中
        HashMap<String, List<AppInfoBean>> QS_APP = new HashMap<String, List<AppInfoBean>>();

        HashMap<String, String> list = new HashMap<String, String>();
        javax.swing.table.DefaultTableModel model = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        int allcount = model.getRowCount();
        for (int i = allcount - 1; i >= 0; i--) {
            String name = (String) model.getValueAt(i, 0);
            String path = (String) model.getValueAt(i, 1);
            String VolumeOfUse = (String) model.getValueAt(i, 2);
            int num = Integer.parseInt(VolumeOfUse);

            List<AppInfoBean> pathlist = (List<AppInfoBean>) QS_APP.get(name);
            if (pathlist == null || pathlist.isEmpty()) {
                pathlist = new ArrayList<AppInfoBean>();
                AppInfoBean appinfo = new AppInfoBean();
                appinfo.setPath(path);
                appinfo.setVolumeOfUse(num);
                pathlist.add(appinfo);
                QS_APP.put(name, pathlist);
            } else {
                AppInfoBean appinfo = new AppInfoBean();
                appinfo.setPath(path);
                appinfo.setVolumeOfUse(num);
                pathlist.add(appinfo);
                QS_APP.put(name, pathlist);
            }
        }
        GlobalVar.APPLICATIONS = QS_APP;
        //logger.debug(QS_APP);
        //logger.debug(GlobalVar.APPLICATIONS);
        DataUtil.updateAppsFile();
        //关闭QuickStartJFrame实例
        QuickStartJFrame qs = QuickStartJFrame.getInstance();
        qs.updateData();

        canceljButtonActionPerformed(evt);

    }//GEN-LAST:event_savejButtonActionPerformed

    private void scanjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scanjButtonActionPerformed
        // TODO add your handling code here:
        QuickStartSettingJDialog qs = QuickStartSettingJDialog.getInstance(true);
        qs.setVisible(true);
    }//GEN-LAST:event_scanjButtonActionPerformed

    private void addTableRow(File file) {
        Object[] obj = new Object[3];
        obj[0] = file.getName().toLowerCase(Locale.CHINESE);
        obj[1] = file.getPath();
        obj[2] = "0";

        ((javax.swing.table.DefaultTableModel) jTable1.getModel()).addRow(obj);

    }

    private boolean isExistPath(File file) {
        boolean exist = false;
        javax.swing.table.DefaultTableModel model = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        int allcount = model.getRowCount();
        for (int i = allcount - 1; i >= 0; i--) {
            Object temp = model.getValueAt(i, 1);
            if (temp.toString().equals(file.getPath())) {
                exist = true;
                break;
            }
        }
        return exist;
    }

    /**
     * 初始化表格数据
     */
    public void initTableData() {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.getDataVector().removeAllElements();
        Iterator i = GlobalVar.APPLICATIONS.entrySet().iterator();
        while (i.hasNext()) {
            Object[] obj = new Object[3];
            java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
            String key = (String) entry.getKey(); //返回与此项对应的键
            List<AppInfoBean> pathlist = (List<AppInfoBean>) entry.getValue(); //返回与此项对应的值
            for (AppInfoBean value : pathlist) {
                obj[0] = key;
                obj[1] = value.getPath();
                obj[2] = String.valueOf(value.getVolumeOfUse());
                model.addRow(obj);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                QuickStartListDialog dialog = new QuickStartListDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addjButton;
    private javax.swing.JButton canceljButton;
    private javax.swing.JButton deljButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton savejButton;
    private javax.swing.JButton scanjButton;
    // End of variables declaration//GEN-END:variables
}
